#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cassert>
#include <cstring>
#include <string>
#include <sys/types.h>

int main()
{
    // 创建管道
    int pipefd[2] = { 0 };
    int n = pipe(pipefd);
    if (n < 0)
    {
        std::cout << "pipe error:" << errno << ": " << strerror(errno) << std::endl;
    }
    std::cout << "pipefd[0]:" << pipefd[0] << std::endl; // 读端
    std::cout << "pipefd[1]:" << pipefd[1] << std::endl; // 写端

    // 创建子进程
    pid_t id = fork();
    assert(id != -1);
    if (id == 0)
    {   
        // 关闭不需要的fd，父进程读取，子进程写入
        close(pipefd[0]);

        // 开始通信
        // const std::string namestr = "hello，我是子进程";
        // int cnt = 1;
        //char buffer[1024];
        char x = 'X';
        int cnt = 0;
        while (true)
        {
            //snprintf(buffer, sizeof buffer, "%s, 计数器:%d, PID: %d", namestr.c_str(), cnt++, getpid());
            // write(pipefd[1], buffer, strlen(buffer));
            write(pipefd[1], &x, 1);
            std::cout << "cnt:" << cnt++ << std::endl;
            //sleep(1);
        }
        close(pipefd[1]);
        exit(0);
    }

    // 关闭不需要的fd，父进程读取，子进程写入
    close(pipefd[1]);

    // 开始通信
    char buffer[1024];
    while (true)
    {
        sleep(10);
        int n = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << "我是父进程，child give me: " << buffer << std::endl;
            sleep(1);
        }
    }
    close(pipefd[0]);
    return 0;
}